package view.listeners;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.JTree;
import javax.swing.tree.TreePath;

import model.HostAddress;
import model.Subnet;

import controller.Controller;

import view.GuiBuilder;
import view.MainFrame;
import view.components.IpAddressTable;
import view.components.IpAddressTablePopup;
import view.components.NetworkTree;
import view.components.NetworkTreePopUp;

public class TreeListener extends MouseAdapter {
	private NetworkTree tree;
	private IpAddressTable table;

	public void setTable(IpAddressTable table) {
		this.table = table;
	}

	public void setTree(NetworkTree tree) {
		this.tree = tree;
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		TreePath item = ((JTree) e.getSource()).getPathForLocation(e.getX(),
				e.getY());

		MainFrame frame = Controller.getInstance().getGuiBuilder().getFrame();

		if (e.getButton() == 3) {
			new NetworkTreePopUp(e.getXOnScreen() - frame.getX(),
					e.getYOnScreen() - frame.getY(), item, tree);

		}

		if (item != null) {
			String ipAddress = item.getLastPathComponent().toString();
			Subnet subnet = tree.getSubnetFromAddress(ipAddress);
			if (subnet != null)
				Controller.getInstance().getGuiBuilder()
						.setStatusText(ipAddress + " / " + subnet.getName());
			else
				Controller.getInstance().getGuiBuilder().setStatusText("");
			if (e.getButton() == 1) {
				if (table != null) {
					table.clearTable();
					if (tree.getSelectedNode().getLevel() > 1) {

						table.loadTable(subnet, 0);

					}
				}
			}

		}
	}

}
